//
//  HomeCollectionViewCell.m
//  GiftSay
//
//  Created by dllo on 16/1/9.
//  Copyright © 2016年 liyinkai. All rights reserved.
//

#import "HomeCollectionViewCell.h"
#import "HomeNewModel.h"
#import "LykLunBoTu.h"
#import "LykZhuanTiView.h"
#import "HomeBannerModel.h"
#import "HomeSecondBannerModel.h"
//#import "LongTableViewCell.h"
@interface HomeCollectionViewCell ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
//tableview方向判断
@property (nonatomic, assign) CGFloat contenty;
//下拉刷新
@property (nonatomic, strong) UIView *downLoad;
//box
@property (nonatomic, strong) UIImageView *box;
//heart
@property (nonatomic, strong) UIImageView *heart;
//boxarray
@property (nonatomic, strong) NSMutableArray *boxArray;
//banner图片数组
@property (nonatomic, strong) NSMutableArray *bannerData;
//专题数组
@property (nonatomic, strong) NSMutableArray *secondBannerData;
//分区头数组
@property (nonatomic, strong) NSMutableArray *sectionTitleArray;
//新品数据数组
@property (nonatomic, strong) NSMutableArray *allNewArray;
@end
//限制一次刷新
static int scrolltimes = 0;
//现在数据个数
static int numOfAll = 0;
@implementation HomeCollectionViewCell

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        //    数组初始化
        self.bannerData = [[NSMutableArray alloc] initWithCapacity:0];
        self.secondBannerData = [[NSMutableArray alloc] initWithCapacity:0];
        self.sectionTitleArray = [[NSMutableArray alloc] initWithCapacity:0];
        self.allNewArray = [[NSMutableArray alloc] initWithCapacity:0];
        //    网络请求
        [self netWorkingForBanner:KHomeBanner];
        [self netWorkingForBanner:KHomeSecondBanner];
        [self netWorkingAll:KHomeAll withLimit:@"20" withAd:@"2" withGender:@"1" withOffset:[NSString stringWithFormat:@"%d", numOfAll] withGeneration:@"1"];
        
        //    tableview
        self.tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStyleGrouped];
        [self.tableView registerClass:[LongTableViewCell class] forCellReuseIdentifier:@"LongTableViewCell"];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.separatorStyle = NO;
        self.tableView.backgroundColor = [UIColor colorWithRed:239 / 255.0 green:239 / 255.0 blue:244 alpha:1];
        [self addSubview:self.tableView];
        
        //    下拉刷新
        self.downLoad = [[UIView alloc] initWithFrame:CGRectZero];
        self.downLoad.backgroundColor = [UIColor clearColor];
        [self addSubview:self.downLoad];
        [self bringSubviewToFront:self.downLoad];
        
        self.box = [[UIImageView alloc] initWithFrame:CGRectZero];
        self.box.image = [UIImage imageNamed:@"box_01.png"];
        [self.downLoad addSubview:self.box];
        
        self.heart = [[UIImageView alloc] initWithFrame:CGRectZero];
        self.heart.image = [UIImage imageNamed:@"heart.png"];
        self.heart.alpha = 0;
        [self.downLoad addSubview:self.heart];
        
        self.boxArray = [[NSMutableArray alloc] initWithCapacity:0];
        for (int i = 1; i < 6; i++) {
            NSString *str = [[NSString alloc] initWithFormat:@"box_%02d.png", i];
            UIImage *image = [UIImage imageNamed:str];
            [self.boxArray addObject:image];
        }
        for (int i = 0; i < 30; i++) {
            UIImage *image = [UIImage imageNamed:@"box_05.png"];
            [self.boxArray addObject:image];
        }
        for (int i = 4; i > 0; i--) {
            NSString *str = [[NSString alloc] initWithFormat:@"box_%02d.png", i];
            UIImage *image = [UIImage imageNamed:str];
            [self.boxArray addObject:image];
        }
    }
    return self;
}

#pragma mark -- 创建组件
-(void)creatItem {
    //    轮播图
    LykLunBoTu *lunBoTu = [[LykLunBoTu alloc] initWithFrame:CGRectMake(0, 0, self.width, self.width / 2.5) withBannerData:self.bannerData];
    lunBoTu.backgroundColor = [UIColor redColor];
    
    //    专题collection
    LykZhuanTiView *zhuanTiView = [[LykZhuanTiView alloc] initWithFrame:CGRectMake(0, lunBoTu.height, self.width, self.width / 3.8) withBannerData:self.secondBannerData];
    
    //    tableview头视图
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.width / 1.45)];
    [view addSubview:lunBoTu];
    [view addSubview:zhuanTiView];
    self.tableView.tableHeaderView = view;
    
    
}

#pragma mark -- tableView协议
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LongTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LongTableViewCell"];
    NSMutableArray *cellArray = [[NSMutableArray alloc] initWithCapacity:0];
    for (int i = 0; i < self.allNewArray.count; i++) {
        NSTimeInterval time = [[self.allNewArray[i] created_at] doubleValue];
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
        NSString *timer = [date description];
        NSRange range = {0, 10};
        timer = [timer substringWithRange:range];
        if ([timer isEqualToString:self.sectionTitleArray[indexPath.section]]) {
            [cellArray addObject:self.allNewArray[i]];
        }
    }
    cell.model = cellArray[indexPath.row];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger a = 0;
    for (int i = 0; i < self.allNewArray.count; i++) {
        NSTimeInterval time = [[self.allNewArray[i] created_at] doubleValue];
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
        NSString *timer = [date description];
        NSRange range = {0, 10};
        timer = [timer substringWithRange:range];
        if ([timer isEqualToString:self.sectionTitleArray[section]]) {
            a++;
        }
    }
    return a;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionTitleArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return self.width / 9.4;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.width / 2;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    //    日期
    UIView *dataView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.width / 9.4)];
    dataView.backgroundColor = [UIColor whiteColor];
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, (dataView.height - dataView.height / 3 * 2) / 2, 5, dataView.height / 3 * 2)];
    line.backgroundColor = [UIColor colorWithRed:253 / 255.0 green:125 / 255.0 blue:167 / 255.0 alpha:1];
    [dataView addSubview:line];
    UILabel *data = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, self.width / 2, 17 * SCREEN_WIDTH)];
    data.frame = CGRectMake(10, (dataView.height - data.height) / 2, self.width / 2, 17 * SCREEN_WIDTH);
    data.text = self.sectionTitleArray[section];
    [dataView addSubview:data];
    return dataView;
}

#pragma mark -- 上拉加载
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.contenty = scrollView.contentOffset.y;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > self.contenty) {
        NSLog(@"加载数据");
        if (scrollView.contentOffset.y > scrollView.contentSize.height - 700) {
            //加载更多数据
            if (scrolltimes == 0) {
                numOfAll = numOfAll + 20;
                [self netWorkingAll:KHomeAll withLimit:@"20" withAd:@"2" withGender:@"1" withOffset:[NSString stringWithFormat:@"%d", numOfAll] withGeneration:@"1"];
                scrolltimes = 1;
            }
        }
    }
    if (scrollView.contentOffset.y < 0) {
        self.downLoad.frame = CGRectMake(0, 0, self.width, 0 - scrollView.contentOffset.y);
        self.box.frame = CGRectMake((self.width - self.width / 10) / 2, 0 - scrollView.contentOffset.y - self.width / 10 / 1.23, self.width / 10, self.width / 10 / 1.23);
        self.heart.frame = CGRectMake((self.width - self.box.width / 4 * 2) / 2, 0 - scrollView.contentOffset.y - self.width / 10 / 1.23, self.box.width / 4 * 2, self.box.height / 4 * 3);
    }
}

#pragma mark -- 下拉刷新
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < -60) {
        [scrollView setContentOffset:CGPointMake(0, -60) animated:YES];
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < 0) {
        NSLog(@"下拉刷新");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.3 animations:^{
                [UIView setAnimationDelay:0];
                self.heart.frame = CGRectMake((self.width - self.box.width / 4 * 2) / 2, 0 - scrollView.contentOffset.y - self.width / 10 / 1.23 - self.box.height / 4 * 3, self.box.width / 4 * 2, self.box.height / 4 * 3);
                self.heart.alpha = 1;
            } completion:^(BOOL finished) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self.heart.alpha = 0;
                });
            }];
        });
        
        [self.box setAnimationImages:self.boxArray];
        [self.box setAnimationDuration:1];
        [self.box setAnimationRepeatCount:1];
        [self.box startAnimating];
        
        numOfAll = 0;
        [self.sectionTitleArray removeAllObjects];
        [self.allNewArray removeAllObjects];
        [self netWorkingAll:KHomeAll withLimit:@"20" withAd:@"2" withGender:@"1" withOffset:[NSString stringWithFormat:@"%d", 0] withGeneration:@"1"];
    }
    
}

#pragma mark -- 网络请求(header)
-(void)netWorkingForBanner:(NSString *)url {
    [LYKNetWorkTool getWithUrl:url parameter:nil httpHeader:nil resposeType:ResponseTypeJSON success:^(id result) {
        NSDictionary *allDic = [[NSDictionary alloc] initWithDictionary:result];
        NSDictionary *bannerDic = allDic[@"data"];
        if ([url isEqualToString:KHomeBanner]) {
            NSArray *bannerArray = bannerDic[@"banners"];
            for (NSDictionary *dic in bannerArray) {
                HomeBannerModel *model = [[HomeBannerModel alloc] initWithDictionary:dic];
                [self.bannerData addObject:model];
            }
        } else if ([url isEqualToString:KHomeSecondBanner]) {
            NSArray *bannerArray = bannerDic[@"secondary_banners"];
            for (NSDictionary *dic in bannerArray) {
                HomeSecondBannerModel *model = [[HomeSecondBannerModel alloc] initWithDictionary:dic];
                [self.secondBannerData addObject:model];
            }
        }
        if (self.bannerData.count > 0 && self.secondBannerData.count > 0) {
            [self creatItem];
        }
        
    } fail:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

#pragma mark -- 网络请求（正文）
-(void)netWorkingAll:(NSString *)url withLimit:(NSString *)limit withAd:(NSString *)ad withGender:(NSString *)gender withOffset:(NSString *)offset withGeneration:(NSString *)generation {
    NSString *urlAll = [NSString stringWithFormat:@"%@limit=%@&ad=%@&gender=%@&offset=%@&generation=%@", url, limit, ad, gender, offset, generation];
    [LYKNetWorkTool getWithUrl:urlAll parameter:nil httpHeader:nil resposeType:ResponseTypeJSON success:^(id result) {
        NSDictionary *allDic = [[NSDictionary alloc] initWithDictionary:result];
        NSDictionary *bannerDic = allDic[@"data"];
        NSArray *AllArray = bannerDic[@"items"];
        for (NSDictionary *dic in AllArray) {
            HomeNewModel *model = [[HomeNewModel alloc] initWithDictionary:dic];
            //            处理分区头题目数据
            NSTimeInterval time = [model.created_at doubleValue];
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
            NSString *timer = [date description];
            NSRange range = {0, 10};
            timer = [timer substringWithRange:range];
            if (![[self.sectionTitleArray lastObject] isEqualToString:timer]) {
                [self.sectionTitleArray addObject:timer];
            }
            //            保存获取数据
            [self.allNewArray addObject:model];
        }
        if (self.allNewArray.count == 20) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
            });
            
        }
        scrolltimes = 0;
        [self.tableView reloadData];
    } fail:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    self.tableView.frame = self.bounds;
}

@end
